package com.example.demo.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.R;
import com.example.demo.dto.FoodDto;
import com.example.demo.entity.Carousel;
import com.example.demo.entity.Food;
import com.example.demo.mapper.CarouselMapper;
import com.example.demo.service.CarouselService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/carousel")
@Slf4j
@CrossOrigin(origins = "*",maxAge = 3600)
public class CarouselController {

    @Autowired
    private CarouselService carouselService;

    @Autowired
    private CarouselMapper carouselMapper;

    /**
     * 查到所有
     * @return
     */
    @GetMapping("/all")
    public R<List<Carousel>> getAll(){
        List<Carousel> carousels = carouselMapper.selectList(null);
        return R.success(carousels);
    }

    /**
     * 轮播图分页查询
     * @param page
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String title) {
        log.info("page = {},pageSize = {},title = {}" ,page,pageSize,title);

        Page<Carousel> carouselList = carouselService.getCarouselList(page, pageSize, title);

        return R.success(carouselList);
    }

    /**
     * 根据ID查询图片信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Carousel> getById(@PathVariable Long id){
        log.info("根据id查询图片信息...");

        Carousel carouselById = carouselService.getCarouselById(id);

        return R.success(carouselById);
    }


    /**
     * 新增图片
     * @param carousel
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('admin')") //用户权限
    public R<String> save(@RequestBody Carousel carousel){
        log.info("新增图片，图片信息：{}",carousel.toString());

        carouselService.addCarousel(carousel);

        return R.success("新增图片成功");
    }

    /**
     * 更新图片
     * @param carousel
     * @return
     */
    @PatchMapping
    @Transactional
    @PreAuthorize("hasAuthority('admin')") //用户权限
    public R<String> update(@RequestBody Carousel carousel){
        log.info("修改图片，图片信息：{}",carousel.toString());

        Integer id = carousel.getId();
        if (StringUtils.isNotEmpty(String.valueOf(id))) {
            return R.error("ID不能为空");
        }

        carouselService.updateCarousel(carousel);

        return R.success("修改图片成功");
    }


}
